package com.weasel.weixin.commons.helper;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.apache.commons.lang.StringUtils;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * Created by Dylan on 2015/10/12.
 */
public final class WeixinMessageDuplicateChecker {

    private final static long CACHE_TIME = 5 * 3;//5秒没回复，微信会重新发消息发3次。


    private final static Cache<Long,Long> cache = CacheBuilder.newBuilder().expireAfterWrite(CACHE_TIME, TimeUnit.SECONDS).maximumSize(Integer.MAX_VALUE).build();


    public static boolean duplicate(final long msgId) {

        try {
            long cacheMsgId = cache.get(msgId, new Callable<Long>() {
                                    @Override
                                    public Long call() throws Exception {
                                        cache.put(msgId,msgId);  //如果不存在，就把msgId缓存起来，并返回空值
                                        return -1L;
                                    }
                                });

            return cacheMsgId == msgId;
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return false;
    }
    private WeixinMessageDuplicateChecker(){}
}
